const Service = require('egg').Service

class UserService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	async index(params) {
		let { pageSize = 10, pageNum = 1 } = params
		pageSize = Number(pageSize)
		const offset = (pageNum - 1) * pageSize
		const data = await this.ctx.model.User.findAndCountAll({
			attributes: { exclude: ['password'] },
			limit: pageSize,
			offset,
		})
		return data
	}

	async create(body) {
		const { username, password } = body
		const hasOneSameName = await this.ctx.model.User.findOne({
			where: { username },
		})
		if (hasOneSameName == null) {
			const encryptPassword = this.ctx.helper.encrypt(password)
			await this.ctx.model.User.create({
				...body,
				password: encryptPassword,
			})
            await this.ctx.model.UserInfo.create({
                userId: id,
                name: username,
            })
			return 'success'
		}
		return '存在相同数据'
	}

	async destroy(id) {
		const hasOne = await this.ctx.model.User.findOne({
			where: { id },
		})
		if (hasOne) {
			await this.ctx.model.User.destroy({
				where: { id },
			})
			return 'success'
		}
		return '不存在该数据'
	}

	async update(id, body) {
		const hasOne = await this.ctx.model.User.findOne({
			where: { id },
		})
		if (hasOne) {
			await this.ctx.model.User.update(
				{ ...body },
				{
					where: { id },
				}
			)
			return 'success'
		}
		return '不存在该数据'
	}
}

module.exports = UserService
